package cn.zmit.kuxi.activity;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.xdroid.activity.XDroidBaseActivity;
import com.xdroid.common.utils.AnimationUtils;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ScreenUtils;
import com.xdroid.common.utils.SystemUtils;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import com.xdroid.utils.AppManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.LinearLayout.LayoutParams;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.entity.CityModel;
import cn.zmit.kuxi.entity.DistrictModel;
import cn.zmit.kuxi.entity.ProvinceModel;
import cn.zmit.kuxi.interfaces.CreateDailogView;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.service.XmlParserHandler;
import cn.zmit.kuxi.widget.CustomProgressDialog;
import cn.zmit.kuxi.widget.TitleBar;

/** * @author @parameter * @return */
public class BaseActivity extends XDroidBaseActivity {
	public Context context;
	/** 全局的LayoutInflater对象，已经完成初始化. */
	public LayoutInflater mInflater;
	String userid;
	/** 总布局. */
	public RelativeLayout rl_base = null;
	// 标题
	private TitleBar titleBar;
	protected Handler mhandler = null;
	// 标题栏布局
	private FrameLayout titleBarFrameLayout = null;
	/** 主内容布局. */
	protected RelativeLayout contentLayout = null;
	private Boolean mHasLogged = false; // 是否已登录
	private CustomProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		AppManager.getInstance().addActivity(this);
		context = this;
		mInflater = LayoutInflater.from(this);
		titleBar = new TitleBar(this);
		// 标题栏布局
		titleBarFrameLayout = new FrameLayout(this);
		titleBarFrameLayout.setId(0x111);
		titleBarFrameLayout.addView(titleBar, new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

		// 最外层布局
		rl_base = new RelativeLayout(this);
		rl_base.setBackgroundColor(Color.rgb(255, 255, 255));

		// 内容布局
		contentLayout = new RelativeLayout(this);
		contentLayout.setPadding(0, 0, 0, 0);

		// 填入View
		rl_base.addView(titleBarFrameLayout, new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

		titleBarFrameLayout.setVisibility(View.GONE);

		RelativeLayout.LayoutParams layoutParamsContent = new RelativeLayout.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		layoutParamsContent.addRule(RelativeLayout.BELOW,
				titleBarFrameLayout.getId());
		rl_base.addView(contentLayout, layoutParamsContent);

		// 设置ContentView
		setContentView(rl_base, new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		Boolean hasLog = PreferenceHelper.readBoolean(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (hasLog) {
			userid = PreferenceHelper.readString(context,
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
		}

	}

	/**
	 * 检测网络,为true则有网
	 */
	public Boolean checkNet() {
		if (SystemUtils.checkNet(context)) {
			return true;
		}
		ToastUtils.show(context, "未检测到网络连接!");
		return false;
	}

	/**
	 * 检测是否已登录
	 * 
	 * @return
	 */
	public Boolean checkLogged() {
		mHasLogged = PreferenceHelper.readBoolean(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		return mHasLogged;
	}

	/**
	 * 检测是否需要执行登录操作 （默认返回true，需要执行登录操作）
	 * 
	 * @return
	 */
	public Boolean checkNeedToLogin() {
		return PreferenceHelper.readBoolean(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.NEED_LOGGED,
				true);
	}

	/**
	 * 获取一个进度条对话框
	 * 
	 * @return
	 */
	public Dialog getProgressDialog() {
		return getProgressDialog("加载中...");
	}

	/**
	 * 获取一个进度条对话框
	 * 
	 * @param message
	 *            显示文字
	 * @return
	 */
	public Dialog getProgressDialog(String message) {
		CustomProgressDialog progressDialog = CustomProgressDialog
				.createDialog(context);
		progressDialog.setMessage(message);
		progressDialog.setCancelable(true);
		progressDialog.setCanceledOnTouchOutside(false);
		return progressDialog;
	}

	/**
	 * 显示进度条对话框
	 */
	public void showProgressDialog() {
		showProgressDialog("加载中...", true, null);
	}

	/**
	 * 显示进度条对话框
	 * 
	 * @param message
	 *            显示文字
	 */
	public void showProgressDialog(String message) {
		showProgressDialog(message, true, null);
	}

	/**
	 * 显示进度条对话框
	 * 
	 * @param message
	 * @param cancel
	 */
	public void showProgressDialog(String message, boolean cancel,
			OnCancelListener cancelListener) {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(context);
		}
		progressDialog.setMessage(message);
		progressDialog.setCancelable(cancel);
		progressDialog.setCanceledOnTouchOutside(false);
		if (cancelListener != null) {
			progressDialog.setOnCancelListener(cancelListener);
		}
		if (!progressDialog.isShowing()) {
			progressDialog.show();
		}
	}

	/**
	 * 销毁进度条对话框
	 */
	public void dismissProgressDialog() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

	/**
	 * 显示自定义对话框（重载）
	 */
	public Dialog showCustomDialog(CreateDailogView createDailogView) {
		return showCustomDialog(true, true, createDailogView);
	}

	/**
	 * 显示自定义对话框（重载）
	 * 
	 * @param mCancelable
	 */
	public Dialog showCustomDialog(boolean mCancelable,
			CreateDailogView createDailogView) {
		return showCustomDialog(true, mCancelable, createDailogView);
	}

	/**
	 * 显示自定义对话框（重载）
	 * 
	 * @param mCanceledOnTouchOutside
	 */
	public Dialog showCustomDialog(Boolean mCanceledOnTouchOutside,
			CreateDailogView createDailogView) {
		return showCustomDialog(mCanceledOnTouchOutside, true, createDailogView);
	}

	/**
	 * 显示自定义对话框
	 * 
	 * @param mCanceledOnTouchOutside
	 *            触碰外围是否可销毁
	 * @param mCancelable
	 *            点击返回是否可销毁
	 */
	public Dialog showCustomDialog(Boolean mCanceledOnTouchOutside,
			Boolean mCancelable, CreateDailogView createDailogView) {
		Dialog dialog = new Dialog(context, R.style.style_custom_dialog);
		dialog.setContentView(createDailogView.createDialogView());
		dialog.setCanceledOnTouchOutside(mCanceledOnTouchOutside);
		dialog.setCancelable(mCancelable);
		dialog.show();
		return dialog;
	}

	/**
	 * 所有省
	 */
	protected String[] mProvinceDatas;
	protected String[] mProvinceId;
	/**
	 * key - 省 value - 市
	 */
	protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
	protected Map<String, String[]> mCitisDatasMapId = new HashMap<String, String[]>();
	/**
	 * key - 市 values - 区
	 */
	protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();
	protected Map<String, String[]> mDistrictDatasMapId = new HashMap<String, String[]>();
	/**
	 * key - 区 values - 邮编
	 */
	protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

	/**
	 * 当前省的名称
	 */
	protected String mCurrentProviceName;
	/**
	 * 当前市的名称
	 */
	protected String mCurrentCityName;
	/**
	 * 当前区的名称
	 */
	protected String mCurrentDistrictName = "";
	protected String mCurrentDistrictId;
	/**
	 * 当前区的邮政编码
	 */
	protected String mCurrentZipCode = "";

	/**
	 * 解析省市区的XML数据
	 */

	protected void initProvinceDatas() {
		List<ProvinceModel> provinceList = null;
		AssetManager asset = getAssets();
		try {
			InputStream input = asset.open("province_data.xml");
			// 创建一个解析xml的工厂对象
			SAXParserFactory spf = SAXParserFactory.newInstance();
			// 解析xml
			SAXParser parser = spf.newSAXParser();
			XmlParserHandler handler = new XmlParserHandler();
			parser.parse(input, handler);
			input.close();
			// 获取解析出来的数据
			provinceList = handler.getDataList();
			// */ 初始化默认选中的省、市、区
			if (provinceList != null && !provinceList.isEmpty()) {
				mCurrentProviceName = provinceList.get(0).getName();
				List<CityModel> cityList = provinceList.get(0).getCityList();
				if (cityList != null && !cityList.isEmpty()) {
					mCurrentCityName = cityList.get(0).getName();
					List<DistrictModel> districtList = cityList.get(0)
							.getDistrictList();
					mCurrentDistrictName = districtList.get(0).getName();
					mCurrentZipCode = districtList.get(0).getZipcode();
				}
			}
			// */
			mProvinceDatas = new String[provinceList.size()];
			for (int i = 0; i < provinceList.size(); i++) {
				// 遍历所有省的数据
				mProvinceDatas[i] = provinceList.get(i).getName();
				List<CityModel> cityList = provinceList.get(i).getCityList();
				String[] cityNames = new String[cityList.size()];
				for (int j = 0; j < cityList.size(); j++) {
					// 遍历省下面的所有市的数据
					cityNames[j] = cityList.get(j).getName();
					List<DistrictModel> districtList = cityList.get(j)
							.getDistrictList();
					String[] distrinctNameArray = new String[districtList
							.size()];
					DistrictModel[] distrinctArray = new DistrictModel[districtList
							.size()];
					for (int k = 0; k < districtList.size(); k++) {
						// 遍历市下面所有区/县的数据
						DistrictModel districtModel = new DistrictModel(
								districtList.get(k).getName(), districtList
										.get(k).getZipcode());
						// 区/县对于的邮编，保存到mZipcodeDatasMap
						mZipcodeDatasMap.put(districtList.get(k).getName(),
								districtList.get(k).getZipcode());
						distrinctArray[k] = districtModel;
						distrinctNameArray[k] = districtModel.getName();
					}
					// 市-区/县的数据，保存到mDistrictDatasMap
					mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
				}
				// 省-市的数据，保存到mCitisDatasMap
				mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {

		}
	}

	/**
	 * 获取标题栏布局
	 * 
	 * @return 标题栏布局
	 */
	public FrameLayout getTitleBarFrameLayout() {
		titleBarFrameLayout.setVisibility(View.VISIBLE);
		return titleBarFrameLayout;
	}

	/**
	 * 获取标题栏
	 * 
	 * @return 标题栏
	 */
	public TitleBar getTitleBar() {
		return titleBar;
	}

	/**
	 * 设置标题栏(默认显示左侧返回按钮)
	 * 
	 * @param titleText
	 *            标题文字
	 */
	public void setTitleView(String titleText) {
		setTitleView(titleText, true);
	}

	/**
	 * 设置标题栏
	 * 
	 * @param titleText
	 *            标题文字
	 * @param visiableBackImage
	 *            是否显示左侧返回按钮
	 */
	public void setTitleView(String titleText, Boolean visiableBackImage) {
		titleBarFrameLayout.setVisibility(View.VISIBLE);
		titleBar.getTv_title().setText(titleText);
		if (!visiableBackImage) {
			titleBar.getRl_back().setVisibility(View.GONE);
		}
	}

	/**
	 * 设置标题栏
	 * 
	 * @param titleBarView
	 *            自定义TitleBar View
	 */
	public void setTitleView(View titleBarView) {
		titleBarFrameLayout.setVisibility(View.VISIBLE);
		titleBarFrameLayout.removeAllViews();
		titleBarFrameLayout.addView(
				titleBarView,
				new LayoutParams(LayoutParams.MATCH_PARENT, (int) ScreenUtils
						.dpToPx(context, 50)));
	}

	@Override
	public void setContentView(int layoutResID) {
		// TODO Auto-generated method stub
		// super.setContentView(layoutResID);
		View view = LayoutInflater.from(this).inflate(layoutResID, null);
		view.setLayoutParams(new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		contentLayout.addView(view);
	}
	
	public View setContentViewRe(int layoutResID) {
		// TODO Auto-generated method stub
		// super.setContentView(layoutResID);
		View view = LayoutInflater.from(this).inflate(layoutResID, null);
		view.setLayoutParams(new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		contentLayout.addView(view);
		
		return view;
//		return LayoutInflater.from(this).inflate(layoutResID, null);
	}

	public void setContentViewSupper(int layoutResID) {
		super.setContentView(layoutResID);
	}

	/**
	 * 从Bundle中根据键获取字符串值
	 * 
	 * @param key
	 *            键
	 * @return 值
	 */
	public String getTextFromBundle(String key) {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			return bundle.getString(key);
		}
		return "";
	}

	@SuppressWarnings("null")
	public double getDoubleFromBundle(String key) {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			return bundle.getDouble(key);
		}
		return (Double) null;
	}

	/**
	 * 执行对话框动画
	 * 
	 * @param rootView
	 *            背景View
	 * @param contentView
	 *            内容View
	 * @param isShow
	 *            true 执行显示动画 false 执行隐藏动画
	 */
	protected void performDialogAnimation(final RelativeLayout rootView,
			final LinearLayout contentView, final Boolean isShow) {
		float[] floats = null;
		if (isShow) {
			rootView.setVisibility(View.VISIBLE);
			floats = new float[] { 0.0f, 1.0f };
		} else {
			floats = new float[] { 1.0f, 0.0f };
		}
		ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(rootView,
				"alpha", floats[0], floats[1]);
		alphaAnimator.setDuration(500);
		alphaAnimator.start();
		alphaAnimator.addListener(new AnimatorListenerAdapter() {
			@Override
			public void onAnimationEnd(Animator animation) {
				if (isShow) {
					rootView.setVisibility(View.VISIBLE);
				} else {
					rootView.setVisibility(View.GONE);
				}

			}
		});

		if (isShow) {
			AnimationUtils.expandingAnimation(contentView);
		} else {
			AnimationUtils.collapsingAnimation(contentView);
		}

	}

}
